@file:Suppress("SpellCheckingInspection", "MemberVisibilityCanBePrivate")

package com.link.play.fit.ai.utils

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import android.os.Build
import android.os.Looper
import android.os.Process

/**
 *Create by SleepDog on 2024/2/20
 */
@SuppressLint("StaticFieldLeak")
object AppX {
    @PublishedApi
    internal lateinit var applicationContext: Context

    @JvmStatic
    inline val context: Context get() = applicationContext

    val versionName: String by lazy {
        try {
            context.packageManager.getPackageInfo(context.packageName, 0).versionName.toString()
        } catch (e: Exception) {
            LogX.e(e = e)
            ""
        }
    }
    val versionCode: Long by lazy {
        try {
            val info = context.packageManager.getPackageInfo(context.packageName, 0)
            if (Build.VERSION.SDK_INT >= 28) info.longVersionCode else info.versionCode.toLong()
        } catch (e: Exception) {
            LogX.e(e = e)
            0L
        }
    }

    val processName: String by lazy {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Application.getProcessName()
        } else {
            try {
                @SuppressLint("DiscouragedPrivateApi", "PrivateApi")
                val m = Class.forName(
                    "android.app.ActivityThread",
                    false,
                    Application::class.java.classLoader
                )
                    .getDeclaredMethod("currentProcessName")
                m.isAccessible = true
                m.invoke(null) as String
            } catch (e: Exception) {
                val pid = Process.myPid()
                val m = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
                for (p in m.runningAppProcesses) {
                    if (p.pid == pid) {
                        return@lazy p.processName
                    }
                }
                ""
            }
        }
    }

    val mainProcessName: String by lazy {
        context.applicationInfo.processName
    }

    val isMainProcess: Boolean get() = processName == mainProcessName

    inline val isMainThread: Boolean get() = Looper.getMainLooper().thread === Thread.currentThread()

}